package cc.laop.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.util.Date;
import java.util.Map;

@Controller
public class FileUploadController extends BaseController {

	@RequestMapping("admin/upload.do")
	@ResponseBody
	public Map<String, Object> upload(MultipartFile file,
			MultipartHttpServletRequest request) {
		String path = request.getSession().getServletContext()
				.getRealPath("upload");
		String realname = file.getOriginalFilename();
		String suffix = realname.substring(realname.lastIndexOf("."));
		String filename = new Date().getTime() + suffix;
		String type = request.getParameter("type");
		if (StringUtils.isNotEmpty(type)) {
			path = path + File.separator + type;
		}
		File filepath = new File(path);
		if (!filepath.exists()) {
			filepath.mkdirs();
		}
		try {
			file.transferTo(new File(filepath, filename));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Object> map = getMap();
		map.put("filepath", "/upload/" + type + "/" + filename);
		return map;
	}
}
